﻿//Write a program that exchanges bits {p, p+1, …, p+k-1) 
//with bits {q, q+1, …, q+k-1} of given 32-bit unsigned integer.

using System;

namespace ExchangeAllBits
{
    class BitExchange
    {
        static void Main()
        {
            Console.Write("Please enter the number n = ");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine("Your number in binary is: " + Convert.ToString(n, 2));
            Console.Write("Exchange bits p = ");
            int p = int.Parse(Console.ReadLine());
            Console.Write("with bits q = ");
            int q = int.Parse(Console.ReadLine());
            Console.Write("Please enter the k: ");
            int k = int.Parse(Console.ReadLine());

            int pVal, qVal;

            for (int i = 0; i <= k; i++)
            {
                pVal = (n >> p + i) & 1;
                qVal = (n >> q + i) & 1;
                n = n & (~(1 << q + i)) | (pVal << q + i);
                n = n & (~(1 << p + i)) | (qVal << p + i);
            }

            Console.WriteLine("The new number is: {0}", n);
            Console.WriteLine("The new number in binary is: " + Convert.ToString(n, 2));
        }
    }
}
